import asyncio;
import pathlib;
import tempfile;
import zipfile;

from ...apt import apt;
from ...utils import utils;
from ...xdg_dir_spec import lib as xdg;

def config():
    bob_home = xdg.get_data_home().joinpath("bob")
    bob_home.mkdir(exist_ok=True)

    src = pathlib.Path(__file__).parent.joinpath("bashrc")
    dist = xdg.get_config_home().joinpath("bashrc.d/bob")
    if dist.exists():
        dist.unlink()
    dist.symlink_to(src)

async def main():
    await apt.ensure_pkg("curl")
    await apt.ensure_pkg("jq")

    # # https://github.com/neovim/neovim/wiki/Building-Neovim#build-prerequisites
    # await apt.ensure_pkg("ninja-build") 
    # await apt.ensure_pkg("gettext") 
    # await apt.ensure_pkg("libtool") 
    # await apt.ensure_pkg("libtool-bin") 
    # await apt.ensure_pkg("cmake") 
    # await apt.ensure_pkg("g++") 
    # await apt.ensure_pkg("pkg-config") 
    # await apt.ensure_pkg("unzip") 
    # await apt.ensure_pkg("curl") 
    # await apt.ensure_pkg("doxygen")

    try:
        await utils.async_exec("bob")
        print("skipping Bob installation: already installed")
        return
    except:
        pass

    archive_url = (await utils.async_stdout("gh api repos/MordechaiHadad/bob/releases/latest | jq -r '[.assets[] | select(.name | match(\"linux-x86_64\"))] | first(.[]) | .browser_download_url' ")).strip()

    if archive_url == "":
        raise Exception("cannot locate Bob archive")

    # archive_file_name = pathlib.Path(archive_url.split("/")[-1].strip("\n"))
    executable_path = pathlib.Path("/usr/local/bin/bob")

    with tempfile.TemporaryDirectory() as tempdir:
        tmp_zip_path = pathlib.Path(tempdir).joinpath("bob.zip")

        if not await utils.async_shell(f"curl {archive_url} -L -o {tmp_zip_path}") == 0:
            raise Exception("failed to download bob executable archive")

        zipfile.PyZipFile(str(tmp_zip_path)).extractall(path=tempdir)
        tmp_executable_path = pathlib.Path(tempdir).joinpath("bob-linux-x86_64-openssl").joinpath("bob")

        tmp_executable_path.chmod(0o755)

        if not await utils.async_shell(f"sudo mv {tmp_executable_path} {executable_path}") ==0:
            raise Exception("failed to move executable to /usr/local/bin")

        config();

asyncio.run(main())

